package com.fuxinglianbao.services;

import com.fuxinglianbao.models.CyclePeriod;
import com.fuxinglianbao.models.User;
import java.util.List;

@Service
public class CyclePeriodService {
    @Autowired
    private EntityManager entityManager;

    @Autowired
    private UserService userService;

    @Transactional
    public CyclePeriod createNewCyclePeriod(Long userId, int starLevel) {
        User user = userService.getUser(userId);
        
        // 检查是否已有活跃周期
        CyclePeriod activeCycle = findActiveCycle(userId, starLevel);
        if (activeCycle != null) {
            throw new IllegalStateException("用户在该星级已有活跃周期");
        }

        CyclePeriod cyclePeriod = new CyclePeriod();
        cyclePeriod.setUser(user);
        cyclePeriod.setStarLevel(starLevel);
        
        entityManager.persist(cyclePeriod);
        return cyclePeriod;
    }

    @Transactional(readOnly = true)
    public CyclePeriod findActiveCycle(Long userId, int starLevel) {
        return entityManager.createQuery(
                "SELECT c FROM CyclePeriod c WHERE c.user.id = :userId " +
                "AND c.starLevel = :starLevel AND c.isActive = true", CyclePeriod.class)
                .setParameter("userId", userId)
                .setParameter("starLevel", starLevel)
                .getResultStream()
                .findFirst()
                .orElse(null);
    }

    @Transactional
    public CyclePeriod addMember(Long cycleId, Long userId, Integer position, boolean isHelpPoint, Long helpSourceUserId) {
        CyclePeriod cycle = entityManager.find(CyclePeriod.class, cycleId);
        if (cycle == null) {
            throw new IllegalArgumentException("周期不存在");
        }

        if (!cycle.isActive()) {
            throw new IllegalStateException("周期已结束");
        }

        User user = userService.getUser(userId);

        // 创建新节点
        TreeNode node = new TreeNode();
        node.setCyclePeriod(cycle);
        node.setUser(user);
        node.setPositionIndex(position);
        node.setIsHelpPoint(isHelpPoint);
        node.setHelpSourceUserId(helpSourceUserId);

        entityManager.persist(node);

        // 更新周期成员数量
        cycle.setCurrentMembersCount(cycle.getCurrentMembersCount() + 1);

        // 检查是否成团
        if (cycle.isCompleted()) {
            cycle.setIsActive(false);
            cycle.setCycleCount(cycle.getCycleCount() + 1);
        }

        return entityManager.merge(cycle);
    }

    @Transactional(readOnly = true)
    public List<TreeNode> getTreeNodes(Long cycleId) {
        return entityManager.createQuery(
                "SELECT n FROM TreeNode n WHERE n.cyclePeriod.id = :cycleId " +
                "ORDER BY n.positionIndex", TreeNode.class)
                .setParameter("cycleId", cycleId)
                .getResultList();
    }

    @Transactional
    public void markAsReceived(Long cycleId) {
        CyclePeriod cycle = entityManager.find(CyclePeriod.class, cycleId);
        if (cycle == null) {
            throw new IllegalArgumentException("周期不存在");
        }

        cycle.setHasReceivedHelp(true);
        entityManager.merge(cycle);
    }

    @Transactional(readOnly = true)
    public List<CyclePeriod> findNearCompletionCycles(Long sourceUserId, int sourceStarLevel) {
        return entityManager.createQuery(
                "SELECT c FROM CyclePeriod c " +
                "WHERE c.isActive = true " +
                "AND c.currentMembersCount = 6 " +
                "AND c.starLevel <= :sourceStarLevel " +
                "AND c.hasReceivedHelp = false " +
                "AND EXISTS (SELECT 1 FROM User u WHERE u.id = c.user.id " +
                "AND EXISTS (SELECT 1 FROM User r WHERE r.referrer.id = :sourceUserId AND u.id = r.id))", 
                CyclePeriod.class)
                .setParameter("sourceStarLevel", sourceStarLevel)
                .setParameter("sourceUserId", sourceUserId)
                .getResultList();
    }

    @Transactional(readOnly = true)
    public List<CyclePeriod> findProgressMadeCycles(Long sourceUserId, int sourceStarLevel) {
        return entityManager.createQuery(
                "SELECT c FROM CyclePeriod c " +
                "WHERE c.isActive = true " +
                "AND c.currentMembersCount >= 3 " +
                "AND c.currentMembersCount < 7 " +
                "AND c.starLevel <= :sourceStarLevel " +
                "AND c.hasReceivedHelp = false " +
                "AND EXISTS (SELECT 1 FROM User u WHERE u.id = c.user.id " +
                "AND EXISTS (SELECT 1 FROM User r WHERE r.referrer.id = :sourceUserId AND u.id = r.id))",
                CyclePeriod.class)
                .setParameter("sourceStarLevel", sourceStarLevel)
                .setParameter("sourceUserId", sourceUserId)
                .getResultList();
    }

    @Transactional(readOnly = true)
    public List<CyclePeriod> findDirectReferralCycles(Long sourceUserId, int sourceStarLevel) {
        return entityManager.createQuery(
                "SELECT c FROM CyclePeriod c " +
                "WHERE c.isActive = true " +
                "AND c.starLevel <= :sourceStarLevel " +
                "AND c.hasReceivedHelp = false " +
                "AND c.user.referrer.id = :sourceUserId " +
                "ORDER BY c.user.registrationTime",
                CyclePeriod.class)
                .setParameter("sourceStarLevel", sourceStarLevel)
                .setParameter("sourceUserId", sourceUserId)
                .getResultList();
    }
}